package org.example.service.impl;

import org.example.Entity.*;
import org.example.mapper.CartMapper;
import org.example.mapper.CommodityMapper;
import org.example.mapper.OrderMapper;
import org.example.service.CartService;
import org.example.utils.GsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<PersonnelOrder> list(String account, String keyword, Integer page_number, Integer page_size) {
        int offset = (page_number - 1)*page_size;

        if (keyword == null || "".equals(keyword)){
            //1.查询所有
            return cartMapper.findList(account,offset,page_size);
        }else {
            //2.模糊查询
            return cartMapper.findByKeyword(account,keyword,offset,page_size);
        }
    }

    @Override
    public Integer add(Integer uid, Integer commodity_id, Integer commodity_count) {
        //1.判断购物车中是否已有该商品
        Cart cart = cartMapper.findByCommodity(uid,commodity_id);

        if (cart != null){
            //2.已有商品，修改数量
            return cartMapper.updateCart(uid,commodity_id,commodity_count);
        }else {
            //3.首次添加商品到购物车
            return cartMapper.addCart(uid, commodity_id, commodity_count);
        }
    }

    @Override
    public Integer delete(Integer uid, Integer commodity_id) {
        return cartMapper.deleteCart(uid, commodity_id);
    }

    @Override
    public Integer pay(Integer uid, List<Integer> commodity_ids) {
        //1.商品订单信息
        List<CommodityOrder> commodity_list = new ArrayList<>();
        //2.计算总价
        float total_price = 0;
        List<Cart> carts = new ArrayList<Cart>();
        for (Integer commodity_id : commodity_ids) {
            Cart cart = cartMapper.findByCommodity(uid,commodity_id);
            if (cart != null){
                Commodity commodity = commodityMapper.findCommodityById(commodity_id);
                total_price += (cart.getCommodity_count() * commodity.getPrice());
                commodity_list.add(new CommodityOrder(commodity.getName(),cart.getCommodity_count(),commodity.getPrice()));
            }
        }
        String commodityStr = GsonUtil.gsonToJSon(commodity_list);
        //3.添加订单
        Integer t1 = orderMapper.addOrder(uid,commodityStr,total_price);
        if (t1<=0)
            return t1;
        //4.移除购物车商品
        for (Integer commodity_id : commodity_ids) {
            cartMapper.deleteCart(uid, commodity_id);
        }

        return 1;
    }
}
